package com.example.administrator.demoa;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.Parcelable;
import android.util.Log;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MyService extends Service {
    private final String TAG = "MyService";
    //线程是否存活
    private Boolean isLive = true;
    private MyBinder myBinder;

    @Override
    public IBinder onBind(Intent intent) {
        Log.e(TAG, "onBind");
        myBinder = new MyBinder();
        return myBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG, "onCreate:thread id =" + Thread.currentThread().getId());

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (isLive){
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    Intent intent = new Intent();
                    intent.setAction("TIME_CHANGE");
                    intent.putExtra("TIME", getTimeChange());
                    sendBroadcast(intent);
                }
            }
        }).start();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        isLive = false;
        super.onDestroy();
        Log.e(TAG, "onDestroy");
    }

    private String getTimeChange() {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        return format.format(date);
    }
}

class MyBinder extends Binder{
    public String reverseEveryWord(String str){
        //以空格为分隔符划分数组
        String[] strArray = str.split(" ");
        //将每个字符串进行逆序
        StringBuffer buffer = new StringBuffer();
        for(int i=0; i<strArray.length; i++) {
            buffer.append(reverse(strArray[i])).append(" ");
        }
        return buffer.toString();
    }

    private String reverse(String s) {
        StringBuffer buffer = new StringBuffer();
        for(int i=s.length()-1; i>=0; i--){
            buffer.append(s.charAt(i));
        }
        return buffer.toString();
    }

    public String getTimeChange(){
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        return format.format(date);
    }
}
